from pymysql import connect
from config import *
class DB(object):
    #数据库管理类

    def __init__(self):

        #创建数据库连接
        self.conn = connect(host=DB_HOST,
                port=DB_PORT,
                database=DB_NAME,
                user=DB_USER,
                password=DB_PASSWORD,
                charset='utf8mb4',
                )

        #获取游标
        self.cursor = self.conn.cursor()

    def close(self):
        #释放资源
        self.cursor.close()
        self.conn.close()

    def get_one(self, sql):
        #使用sql语句查询用户信息
        #执行sql语句
        self.cursor.execute(sql)

        #获取查询结果
        query = self.cursor.fetchone()

        if not query:
            return None

        fileds = [filed[0] for filed in self.cursor.description]

        return_data = {}
        for filed, value in zip(fileds, query):
            return_data[filed] = value

        return return_data


if __name__ == '__main__':
    db = DB()
    data = db.get_one("select * from user where user_name = 'Hao Yuning'")
    print(data)
    db.close()


